package models

import (
	"errors"
	"strings"
	"time"

	"gitee.com/lzqysoft/ilive/libs"

	//	"github.com/astaxie/beego"

	"github.com/astaxie/beego/orm"
)

//资源树数据结构
type ResTree struct {
	Name     string    `json:"title"`
	Id       int64     `json:"id"`
	Expand   bool      `json:"expand"`
	Checked  bool      `json:"checked"`
	Children []ResTree `json:"children"`
}

//认证资源树数据结构
type AccessTree struct {
	Name     string       `json:"name"`
	Id       int64        `json:"id"`
	Logo     string       `json:"logo"`
	Children []AccessTree `json:"children"`
}

//根据角色获取所有资源分配情况的树
func GetResTreeByRoleId(roleid int64) *ResTree {

	pid := int64(0)
	tree := new(ResTree)
	getResTreeByRoleIdPid(roleid, pid, tree)
	return tree
}

//根据角色获取该角色具有权限的资源树
func GetAccessTreeByRoleId(roleid int64) *AccessTree {
	access := make([]orm.Params, 0)
	if roleid == 1 {
		_, access = GetAllResourceList(1)
	} else {
		access, _ = GetResourceByRoleId(roleid, 1)
	}
	//	mres, _ := GetResMenu()
	//	//	lv := make(map[string]interface{})
	//	for _, k := range access {
	//		for i, v := range mres {
	//			if k["Id"].(int64) == v["Id"].(int64) {
	//				mres = append(mres[:i], mres[i+1:]...)
	//			}
	//		}
	//	}

	//	access = append(access, mres...)

	pid := int64(0)
	tree := new(AccessTree)
	getAccessTreeByRoleIdPid(access, pid, tree)
	// beego.Debug(tree)
	return tree
}

//登录验证,用户名、密码，返回user和error
func CheckLogin(uname string, pwd string) (user User, err error) {
	user, err = GetUserByUname(uname)

	if err != nil {
		return user, errors.New("没有此用户名！")
	} else {
		if libs.EncodeUserPwd(uname, pwd) != user.Pwd {
			return user, errors.New("密码不正确！")
		}
	}
	return user, nil
}

//递归获取资源树，根据角色id、资源父id，ResTree指针返回
func getResTreeByRoleIdPid(roleid int64, pid int64, pTree *ResTree) {
	reslist, _ := GetResSubTree(pid, 1)
	if len(reslist) < 1 {
		return
	}
	for k, v := range reslist {
		dtree := ResTree{
			v["Name"].(string),
			v["Id"].(int64),
			true,
			GetRoleOwnerResource(roleid, v["Id"].(int64)),
			nil}
		if v["Pid"].(int64) == 0 && v["Type"].(int64) == 1 {
			dtree = ResTree{
				v["Name"].(string),
				v["Id"].(int64),
				true,
				false,
				nil}
		}
		pTree.Children = append(pTree.Children, dtree)
		getResTreeByRoleIdPid(roleid, v["Id"].(int64), &pTree.Children[k])
	}

}

//递归获取资源树，根据角色id、资源父id，AccessTree指针返回
func getAccessTreeByRoleIdPid(access []orm.Params, pid int64, pTree *AccessTree) {

	i := -1
	for k, v := range access {
		dtree := AccessTree{
			v["Name"].(string),
			v["Id"].(int64),
			v["Logo"].(string),
			nil}
		if v["Pid"].(int64) == pid && i < k {
			i++
			pTree.Children = append(pTree.Children, dtree)
			getAccessTreeByRoleIdPid(access, v["Id"].(int64), &pTree.Children[i])
		}
	}

}

//Desc 软删除表
//Param o orm.Ormer
//Param objname string 表名
//Param query map[string]string 筛选条件
//Param uname string 操作者名称
//return num, error 软删除条数
func SoftDelete(o orm.Ormer, objname string, query map[string]interface{}, uname string) (num int64, err error) {
	qs := o.QueryTable(objname)
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	num, err = qs.Update(orm.Params{
		"isDelete": 1,
		"updater":  uname,
		"Utime":    time.Now(),
	})
	return

}
